package com.xinxing.city.recovery.utils;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.xinxing.city.recovery.interfaces.DownloadListener;


import java.io.File;


public class CheckUpdate {
    private final String TAG = "CheckUpdate_检查更新";
    private Context mContext;
    private DownloadManager mDownloadManager;
    private DownloadManager.Request mRequest;
    private int mDownId;
    private String mDownPath;
    private String mDownApkName;
    private DownloadListener downloadListener;

    public CheckUpdate(Context context) {
        this.mContext = context;
    }

    /*
     * 对比apk版本号的方法
     * @param float 要对比的目标版本号
     * @return true=版本号一致,false=版本号不一致
     */
    public boolean CheckVersion(float targetVersion) {
        String packagename = mContext.getPackageName();
        float version = 0;
        try {
            //获取当前apk的版本号,   getPackageInfo = 包信息 :参数为(包名,版本号曾量)
            version = (float) mContext.getPackageManager().getPackageInfo(packagename, 0).versionCode;
            Log.e(TAG, "pkgVersion:" + false);

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        if (version == targetVersion) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * 下载apk的方法
     * @param String downUri ： 参数是下载apk的网络地址Uri
     * @param String downPath ： 参数是存放下载内容的文件目录路径
     * @param String downApkName ： 参数是设置下载完成后的apk名称。注意！名称后面要加.apk后缀名
     * @param DisplayMode displayMode ： 下载模式,推荐使用 DisplayMode.MODE_DIALOG_BOX ,系统的未完善
     *
     */

    public void downNewApk(String downUri, String downPath, String downApkName, DisplayMode displayMode) {

        Log.e(TAG, downPath+"/"+downApkName);
        Log.e(TAG, downUri);
        if (mContext == null) {
            Log.e(TAG, "Error:mContext is null");
            return;
        }
        if (downUri == null) {
            Log.e(TAG, "Error:downUri is null");
            return;
        }
        if (downPath.equals("") && downPath == null) {
            Log.e(TAG, "Error:downPath is null");
            return;
        }
        if (downApkName.equals("") && downApkName == null) {
            Log.e(TAG, "Error:downApkName is null");
        }
        mDownPath = downPath;
        mDownApkName = downApkName;

        if (displayMode == DisplayMode.MODE_DIALOG_BOX) { //使用第三方下载

            dialog(downUri);

        } else if (displayMode == DisplayMode.MODE_STATUS_BAR) {
            //使用系统下载，注意！此系统下载没有写下载完成的广播监听，所以无法自动安装apk
            mDownloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
            //初始化下载的request
            mRequest = new DownloadManager.Request(Uri.parse(downUri));
            //设置允许网络类型   分别是 移动网络 和 WiFi网络
            mRequest.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
            mRequest.setAllowedOverRoaming(false);
            //设置文件类型
            MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
            String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(downUri));
            mRequest.setMimeType(mimeString);
            Log.e(TAG, "选择模式：状态栏");
            mRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);//通知可见性 ，参数为可见度为可见
            mRequest.setShowRunningNotification(true); //设置显示运行通知
            mRequest.setVisibleInDownloadsUi(true); //在下载中设置UI可见的
            //设置下载保存路径
            mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, downApkName);
            mRequest.setTitle(downApkName);
            //插入下载队列.返回下载对象Id
            mDownId = (int) mDownloadManager.enqueue(mRequest);
            Toast.makeText(mContext, "正在更新", Toast.LENGTH_SHORT).show();


        } else {
            Log.e(TAG, "Error:downNewApk @param is null");
            return;
        }
    }

    private void dialog(String url) {
        File file = new File(mDownPath);
        File fileApk = new File(mDownPath+"/" + mDownApkName);
        if (fileApk.exists()) {
            fileApk.delete();
        }
        if (!file.exists()) {
            file.mkdirs();
        }

        FileDownloader.setup(mContext);
        FileDownloader.getImpl()
                .create(url)
                .setPath(mDownPath + "/" + mDownApkName)
                .setListener(new FileDownloadListener() {
                    @SuppressLint("SuspiciousIndentation")
                    @Override //等待    参数 task=下载任务   soFarBytes=当前已经下载字节  totalBytes=总字节
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        mDownId = task.getId();
                        downloadListener.pending(totalBytes);
                    }


                    @Override //增量
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.e(TAG, "pending:接受更新值:  soFarBytes="+soFarBytes+"   totalBytes="+totalBytes);
                        downloadListener.progress(soFarBytes,totalBytes);
                    }

                    @Override //全部下载完成后
                    protected void completed(BaseDownloadTask task) {
                        downloadListener.completed();
                        Log.e(TAG, "completed:下载完成");
                        Toast.makeText(mContext, "下载完毕,开始安装", Toast.LENGTH_LONG).show();
                        installApk();
                    }

                    @Override //暂停
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        Log.e(TAG, "FileDownloader error: " + e);
                        downloadListener.error();
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {

                    }
                }).start();

    }


    public enum DisplayMode {
        MODE_DIALOG_BOX, MODE_STATUS_BAR;
    }

    /**
     * 安装apk
     */
    private void installApk() {
        Log.e(TAG, mDownPath + "/" + mDownApkName);
        File apkfile = new File(mDownPath + "/" + mDownApkName);
//        if (!apkfile.exists()) {
//            return;
//        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //兼容android7.0以上版本
        Uri uri = Uri.fromFile(apkfile);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //通过FileProvider创建一个content类型的Uri
            uri = FileProvider.getUriForFile(mContext, "com.xinxing.city.recovery.fileprovider", apkfile);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }
    public void setDownloadListener(DownloadListener downloadListener){
        this.downloadListener = downloadListener;
    }
}
